package glickrdemo

import org.codehaus.groovy.grails.validation.routines.UrlValidator

class demoTagLib {

    def propTable = {attrs, body ->
        if (attrs.object) {
            def ignore = ['active','metaClass']
            def props  = attrs.object.properties.sort{it.key}.collect{it}.findAll{!ignore.contains(it.key)}

            out << '<table class="properties" cellspacing="0">'
            props.each() { it ->
                out << '<tr>'
                out << '<td class="key">' << it.key << '</td>'
                out << '<td class="value">' << fieldFormat(it.value) << '</td>'
                out << '</tr>'
            }
            out << '</table>'
        }
    }

    private String fieldFormat(def val) {
        // URL
        UrlValidator urlValidator = new UrlValidator();
        if (urlValidator.isValid(val.toString())) {
            return """<a href="${val}" target="_blank">${val}</a>"""
        }
        val = val.toString().encodeAsHTML().replace('\n', '<br/>\n')

        // Default
        return val
    }
}
